import {decryptByDESModeCBC, encryptByDESModeCBCUtf8to64} from "@/common/utils/des";
import {app, dialog} from "electron";
const clientConfig = require('@/common/winUtils/config')
let {config} = clientConfig.getAppConfig()
const fs= require("fs");
const aes = require("@/common/utils/des");
export function configRead() {
  return new Promise((resolve, reject) => {
    fs.readFile(config, "utf8", (err, data) => {
      if(err || !data){
        reject(err)
        return
      }
      const obj = JSON.parse(data);
      if(obj && obj.data){
        const info = JSON.parse(decryptByDESModeCBC(obj.data))
        resolve(info.shopId)
      }else{
        reject()
      }
    });
  })
}
export function configWrite(shopId) {
  return new Promise((resolve, reject) => {
    fs.writeFile(config, JSON.stringify({
      data: encryptByDESModeCBCUtf8to64(JSON.stringify({shopId}))
    }), () => {
      resolve(shopId)
    })
  })
}


export function writeFile(content, path, fileName = '') {
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path, { recursive: true });
  }
  path += '/'+fileName
  // fs.writeFileSync(path, aes.encryptByDESModeCBCUtf8to64(content)+"\n", {flag: 'a', encoding: 'utf8'});
  fs.writeFileSync(path, content+"\n", {flag: 'a', encoding: 'utf8'});
}

export function readFile(file) {
  fs.readFile(file, (err, data) => {
    if (data) {
      let content = data.toString().split("\n")
      content.map(con => {
        fs.writeFileSync('des.log', aes.decryptByDESModeCBC(con)+"\n", {flag: 'a', encoding: 'utf8'})
      })
    }
  })
}

export function writeProcessTrace() {
  process.on("uncaughtException", (err) => {
    console.log(err)
    const path = app.getPath('userData') + '/Log/StackTrace'
    const error = err.stack || err.message || err
    let date = new Date()
    let month = date.getFullYear()+'-'+(date.getMonth()+1) +'-'+ date.getDate()
    const log = `${new Date().toLocaleString()}: ${error}\n\n`
    writeFile(log, path, `/${month}.log`)
    dialog.showErrorBox("网吧超市", "程序运行异常，请尝试重新启动！")
    app.exit(1)
  })
}
